// Server API makes it possible to hook into various parts of Gridsome
// on server-side and add custom data to the GraphQL data layer.
// Learn more: https://gridsome.org/docs/server-api/

// Changes here require a server restart.
// To restart press CTRL + C in terminal and run `gridsome develop`

const axios = require('axios')
const Cookies = require('js-cookie')
const utcToLocal = (time) => {
  let formatNum = (num)=>{
      return num>=10?num:('0'+num)
  }
  let arr = time.split(/[^0-9]/)
  let worldDate = new Date(arr[0], arr[1] - 1, arr[2], arr[3], arr[4], arr[5])
  let localDate = new Date(worldDate.getTime() + 8 * 60 * 60 * 1000)
  return formatNum(localDate.getFullYear()) + "-"
      + formatNum((localDate.getMonth() + 1)) + "-" 
      + formatNum(localDate.getDate()) + " " 
      + formatNum(localDate.getHours()) + ":" 
      + formatNum(localDate.getMinutes()) + ":" 
      + formatNum(localDate.getSeconds())
}
const accessToken = Cookies.get("TOKEN_KEY")
// console.log(accessToken)
module.exports = function (api) {
  // console.log(api)
  // console.log(api.store)
  // console.log(api.store.Store)
  // console.log(api.store.Store.app)
  api.loadSource(async ({ addCollection }) => {
    const gists = addCollection('Gist')
    const followers = addCollection('Fllower')
    const following = addCollection('Fllowing')
    const blogs = addCollection('Blog')
    const projects = addCollection('Project')

    let response = await axios.get(`https://api.github.com/users/GitHub-Laziji/gists?page=1&per_page=1${accessToken ? '&access_token=' + accessToken : ''}`)
    let id = '';
    let result = response.data
    if (!result || result.length == 0) {
        return
    }
    for (let key in result[0].files) {
        id = result[0]['id']
        break
    }
    let detailResponse = await axios.get(`https://api.github.com/gists/${id}${accessToken ? '?access_token=' + accessToken : ''}`)
    let detail = detailResponse.data
    for (let key in detail.files) {
      gists.addNode({
        title: key,
        content: detail.files[key]['content'],
        description: detail['description'],
        createTime: utcToLocal(detail['created_at']),
        updateTime: utcToLocal(detail['updated_at']),
        hide: false
      })
    }

    let followersResponse = await axios.get(`https://api.github.com/users/GitHub-Laziji/followers?page=1&per_page=9999${accessToken ? '&access_token=' + accessToken : ''}`)
    let followersResult = followersResponse.data
    for (let i = 0; i < followersResult.length; i++) {
      followers.addNode({
        name: followersResult[i]['login'],
        avatarUrl: followersResult[i]['avatar_url'],
        htmlUrl: followersResult[i]['html_url']
      })
    }

    let followingResponse = await axios.get(`https://api.github.com/users/GitHub-Laziji/following?page=1&per_page=9999${accessToken ? '&access_token=' + accessToken : ''}`)
    let followingResult = followingResponse.data
    for (let i = 0; i < followingResult.length; i++) {
      following.addNode({
        name: followingResult[i]['login'],
        avatarUrl: followingResult[i]['avatar_url'],
        htmlUrl: followingResult[i]['html_url']
      })
    }

    let blogResponse = await axios.get(`https://api.github.com/users/GitHub-Laziji/gists?page=1&per_page=9999${accessToken ? '&access_token=' + accessToken : ''}`)
    let blogResult = blogResponse.data
    for (let i = 0; i < blogResult.length; i++) {
      // let id = blogResult[i].id;
      // let singleBlogResponse = await axios.get(`https://api.github.com/gists/${id}${accessToken ? '?access_token=' + accessToken : ''}`)
      // let singleBlogResult = singleBlogResponse.data
      for (let key in blogResult[i].files) {
        blogs.addNode({
          id: blogResult[i]["id"],
          title: key,
          url: blogResult[i].files[key],
          description: blogResult[i]["description"],
          createTime: utcToLocal(blogResult[i]["created_at"]),
          updateTime: utcToLocal(blogResult[i]["updated_at"]),
          // content: singleBlogResult.files[key]['content'],
          hide: false
        })
      }
    }

    let projectResponse = await axios.get(`https://api.github.com/users/GitHub-Laziji/repos?page=1&per_page=9999${accessToken ? '&access_token=' + accessToken : ''}`)
    let projectResult = projectResponse.data
    for (let i = 0; i < projectResult.length; i++) {
      // let name = projectResult[i].name;
      // let singleProjectResponse = await axios.get(`https://api.github.com/repos/GitHub-Laziji/${name}/contents/README.md${accessToken ? '?access_token=' + accessToken : ''}`)
      // let singleProjectResult = singleProjectResponse.data
      projects.addNode({
        id: projectResult[i]['id'],
        name: projectResult[i]['name'],
        url: projectResult[i]['html_url'],
        description: projectResult[i]['description'],
        stargazersCount: projectResult[i]['stargazers_count'],
        watchersCount: projectResult[i]['watchers_count'],
        forksCount: projectResult[i]['forks_count'],
        language: projectResult[i]['language'],
        license: projectResult[i]['license'] ? projectResult[i]['license']['spdx_id'] : null,
        createTime: projectResult[i]['created_at'] ? utcToLocal(projectResult[i]['created_at']) : '',
        updateTime: projectResult[i]['updated_at'] ? utcToLocal(projectResult[i]['updated_at']): '',
        // readme_content: singleProjectResult['content'],
        hide: false
      })
    }

  })


  api.createPages(({ createPage }) => {
    // Use the Pages API here: https://gridsome.org/docs/pages-api/
    createPage({
      path: '/',
      component: './src/pages/Index.vue'
    })
    createPage({
      path: '/user/social',
      component: './src/pages/Social/Index.vue'
    })
    createPage({
      path: '/user/social/details/:name',
      component: './src/pages/Social/Details.vue'
    })
    createPage({
      path: '/user/blog',
      component: './src/pages/Blog/Index.vue'
    })
    createPage({
      path: '/user/project',
      component: './src/pages/Project/Index.vue'
    })
  })
}
